<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加 -->
    <el-card>
      <!-- 警告区域 :closable="false"(是否展示“X”号) show-icon(显示图标) -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedCateKeys"
            :options="CateList"
            :props="cascaderProps"
            @change="ParentCateChange"
            clearable
          ></el-cascader>
        </el-col>
        <el-col>
          <el-tabs v-model="activeName" @tab-click="handleTabClick">
            <!-- 添加动态参数的面板 -->
            <el-tab-pane label="动态参数" name="many">
              <el-button
                type="primary"
                :disabled="isButtonDisabled"
                @click="addParamsdialogVisible=true"
              >添加参数</el-button>
              <el-table border :data="ParentCateMlist" style="width: 100%">
                <el-table-column type="expand">
                  <!-- tag添加移除参数 -->
                  <template slot-scope="scope">
                    <!-- 循环渲染标签 -->
                    <el-tag
                      :key="i"
                      v-for="(item,i) in scope.row.attr_vals"
                      closable
                      @close="handleClose(i,scope.row)"
                    >{{item}}</el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveValsInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="primary" @click="editCateDialg(scope.row.attr_id)">编辑</el-button>
                    <el-button type="warning" @click="deleteCateDialog(scope.row.attr_id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <!-- 添加静态参数的面板 -->
            <el-tab-pane label="静态参数" name="only">
              <el-button
                type="primary"
                :disabled="isButtonDisabled"
                @click="addParamsdialogVisible=true"
              >添加属性</el-button>
              <el-table border :data="ParentCateOlist" style="width: 100%">
                <el-table-column type="expand">
                  <!-- tag添加移除参数 -->
                  <template slot-scope="scope">
                    <!-- 循环渲染标签 -->
                    <el-tag
                      :key="i"
                      v-for="(item,i) in scope.row.attr_vals"
                      closable
                      @close="handleClose(i,scope.row)"
                    >{{item}}</el-tag>
                    <el-input
                      class="input-new-tag"
                      v-if="scope.row.inputVisible"
                      v-model="scope.row.inputValue"
                      ref="saveValsInput"
                      size="small"
                      @keyup.enter.native="handleInputConfirm(scope.row)"
                      @blur="handleInputConfirm(scope.row)"
                    ></el-input>
                    <el-button
                      v-else
                      class="button-new-tag"
                      size="small"
                      @click="showInput(scope.row)"
                    >+ New Tag</el-button>
                  </template>
                </el-table-column>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="primary" @click="editCateDialg(scope.row.attr_id)">编辑</el-button>
                    <el-button type="warning" @click="deleteCateDialog(scope.row.attr_id)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-card>
    <!-- 弹框添加属性和参数 -->
    <el-dialog :title="'添加'+textTitle" :visible.sync="addParamsdialogVisible">
      <el-form
        :model="addParamsForm"
        :rules="addParamsRules"
        ref="addParamsRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类的接口 -->
    <el-dialog :title="'修改'+ textTitle" :visible.sync="editDialogVisible" @close="editDialogClosed">
      <el-form
        :model="editCateForm"
        :rules="editCateRules"
        ref="editCateRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="textTitle" prop="attr_name">
          <el-input v-model="editCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editConfirmCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { pathToFileURL } from 'url'
export default {
  data() {
    return {
      activeName: 'many',
      //绑定用户选择的分类值
      selectedCateKeys: [],
      cascaderProps: {
        //选中的绑定数据是id
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      //查询的三级菜单的数据
      //many
      ParentCateMlist: [],
      //only
      ParentCateOlist: [],
      CateList: [],
      //弹框
      addParamsdialogVisible: false,
      addParamsForm: {
        attr_name: ''
      },
      addParamsRules: {
        attr_name: [{ required: true, message: '请填写名称', trigger: 'change' }]
      },

      //编辑页面
      editDialogVisible: false,
      editCateForm: {},
      editCateRules: {
        attr_name: [{ required: true, message: '请填写名称', trigger: 'change' }]
      }
      //标签页的增删改查
      // inputViaible: false,
      // inputValue: ''
    }
  },
  methods: {
    //获取级联的数据
    async getParamsList() {
      const { data: res } = await this.$http.get(`categories`)
      console.log(res.data)
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.CateList = res.data
      console.log(this.CateList)
    },
    handleTabClick() {
      this.getCateData()
    },
    ParentCateChange() {
      this.getCateData()
    },
    async getCateData() {
      console.log(this.selectedCateKeys)
      // 证明选中的不是三级分类
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        this.ParentCateMlist = []
        this.ParentCateOlist = []
        return
      }
      //   console.log(this.selectedId)
      //分类id
      const { data: res } = await this.$http.get(`categories/${this.selectedId}/attributes`, { params: { sel: this.activeName } })
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
        console.table(item.attr_vals)
      })

      if (this.activeName === 'many') {
        this.ParentCateMlist = res.data
      } else if (this.activeName === 'only') {
        this.ParentCateOlist = res.data
      }
      // console.log(res.data)
      // console.log(this.ParentCateMlist)
    },

    //添加参数属性
    async addParams() {
      this.$refs.addParamsRef.validate(async valid => {
        const { data: res } = await this.$http.post(`categories/${this.selectedId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加数据失败')
        this.$message.success('添加数据成功')

        this.addParamsdialogVisible = false
        this.getCateData()
      })
    },
    //编辑标签参数
    async editCateDialg(attrId) {
      //分类id 属性id

      // alert(row.attr_id)
      // alert(row.cat_id)
      const { data: res } = await this.$http.get(`categories/${this.selectedId}/attributes/${attrId}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数信息失败！')
      }
      console.log(res)
      this.editCateForm = res.data
      this.editDialogVisible = true
    },
    editDialogClosed() {
      this.$refs.editCateRef.resetFields()
    },
    editConfirmCate() {
      this.$refs.editCateRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.selectedId}/attributes/${this.editCateForm.attr_id}`, {
          attr_name: this.editCateForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success('更新成功')

        console.log(res)
        this.getCateData()
        this.editDialogVisible = false
      })
    },
    //删除标签
    async deleteCateDialog(attrId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          console.log(attrId)
          const { data: res } = await this.$http.delete(`categories/${this.selectedId}/attributes/${attrId}`)
          if (res.meta.status !== 200) return this.$message.error('删除参数失败')
          this.$message.success('删除成功')
          this.getCateData()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //标签页的增删改
    //删除
    handleClose(i, row) {
      console.log(row.attr_id)
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
      console.log(row)
    },
    //标签页的enter和blur事件
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      //push方法加入数组显示
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    //输入框显示
    showInput(row) {
      console.log(row.attr_id)
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveValsInput.$refs.input.focus()
      })
    },
    //添加
    //发请求保存数据
    async saveAttrVals(row) {
      const { data: res } = await this.$http.put(`categories/${this.selectedId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        // 字符串传参
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
      console.log(res)
      // this.editCateForm = res.data
    }
  },
  computed: {
    //禁用当前按钮
    isButtonDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      } else {
        return false
      }
      //选择三级菜单
    },
    //三级菜单的id
    selectedId() {
      if (this.selectedCateKeys.length === 3) {
        // return this.selectedCateKeys[this.selectedCateKeys.length - 1]
        return this.selectedCateKeys[2]
      }
      return null
    },
    textTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  },
  created() {
    this.getParamsList()
  }
}
</script>
<style lang="less" scoped>
</style>